package com.atguigu.tingshu.album.api;

import com.atguigu.tingshu.album.service.AlbumInfoService;
import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.common.annotation.NeedLogin;
import com.atguigu.tingshu.common.kafka.constant.KafkaConst;
import com.atguigu.tingshu.common.kafka.service.KafkaService;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.common.utils.ThrowUtil;
import com.atguigu.tingshu.dto.AlbumSaveOrUpdateDTO;
import com.atguigu.tingshu.enums.AlbumStatType;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.query.album.AlbumInfoQuery;
import com.atguigu.tingshu.vo.album.AlbumInfoVo;
import com.atguigu.tingshu.vo.album.AlbumListVo;
import com.atguigu.tingshu.vo.album.AlbumStatMqVo;
import com.atguigu.tingshu.vo.album.AlbumStatVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.UUID;

@Tag(name = "专辑管理")
@RestController
@RequestMapping("api/album")
@SuppressWarnings({ "all" })
public class AlbumInfoApiController {

    @Autowired
    private AlbumInfoService albumInfoService;

    @Autowired
    private TrackInfoService trackInfoService;

    @Autowired
    private KafkaService kafkaService;

    @Operation(tags = "新增专辑")
    @PostMapping("/albumInfo/saveAlbumInfo")
    @NeedLogin
    public Result<Boolean> saveAlbumInfo(@RequestBody AlbumSaveOrUpdateDTO albumInfoDTO) {
        // 从 ThreadLocal 中获取用户ID
        Long userId = AuthContextHolder.getUserId();
        return Result.ok(albumInfoService.saveAlbumInfo(userId, albumInfoDTO));
    }

    @Operation(tags = "根据ID查询专辑信息")
    @GetMapping("/albumInfo/getAlbumInfo/{id}")
    // @NeedLogin
    public Result<AlbumInfoVo> getAlbumInfo(@PathVariable Long id) {
        AlbumInfoVo albumInfoVo = albumInfoService.getAlbumInfoById(id);

        // 异步更新专辑播放量统计
        AlbumStatMqVo albumStatMqVo = new AlbumStatMqVo();
        albumStatMqVo.setBusinessNo(UUID.randomUUID().toString().replaceAll("-", ""));
        albumStatMqVo.setAlbumId(id);
        albumStatMqVo.setStatType(AlbumStatType.PLAY_STAT_NUM.getCode());
        albumStatMqVo.setCount(1);
        kafkaService.sendMessage(KafkaConst.TOPIC_ALBUM_STAT_UPDATE, albumStatMqVo);

        return Result.ok(albumInfoVo);
    }

    @Operation(tags = "分页查询用户专辑信息")
    @PostMapping("/albumInfo/findUserAlbumPage/{page}/{limit}")
    @NeedLogin
    public Result<Page<AlbumListVo>> findUserAlbumPage(@PathVariable Long page,
            @PathVariable Long limit,
            @RequestBody AlbumInfoQuery albumInfoQuery) {
        return Result.ok(albumInfoService.findUserAlbumPage(page, limit, albumInfoQuery));
    }

    @Operation(tags = "查询用户所有专辑信息")
    @GetMapping("/albumInfo/findUserAllAlbumList")
    @NeedLogin
    public Result<List<AlbumInfoVo>> findUserAllAlbumList() {
        return Result.ok(albumInfoService.findUserAllAlbumList());
    }

    @DeleteMapping("/albumInfo/removeAlbumInfo/{id}")
    @Operation(tags = "删除专辑信息")
    @NeedLogin
    public Result<?> removeAlbumInfo(@PathVariable Long id) {
        // 鉴权，只有专辑用户才能删除
        Long userId = AuthContextHolder.getUserId();
        AlbumInfoVo albumInfo = albumInfoService.getAlbumInfoById(id);
        ThrowUtil.throwIf(albumInfo == null, ResultCodeEnum.DATA_ERROR, "专辑不存在");
        ThrowUtil.throwIf(!userId.equals(albumInfo.getUserId()), ResultCodeEnum.PERMISSION, "无权限删除该专辑");
        // 专辑下是否包含音乐
        List<TrackInfo> trackInfoList = trackInfoService.list(new LambdaQueryWrapper<TrackInfo>()
                .eq(TrackInfo::getAlbumId, id));
        ThrowUtil.throwIf(trackInfoList.size() > 0, ResultCodeEnum.DATA_ERROR, "专辑下包含音乐，请先删除专辑下的音乐");
        return Result.ok(albumInfoService.removeAlbumInfo(id) ? Result.ok() : Result.fail());
    }

    @PutMapping("/albumInfo/updateAlbumInfo/{id}")
    @Operation(tags = "更新专辑信息")
    @NeedLogin
    public Result<?> updateAlbumInfo(@PathVariable Long id, @RequestBody AlbumSaveOrUpdateDTO albumSaveOrUpdateDTO) {
        // 鉴权，只有专辑用户才能更新
        Long userId = AuthContextHolder.getUserId();
        AlbumInfoVo albumInfo = albumInfoService.getAlbumInfoById(id);
        ThrowUtil.throwIf(albumInfo == null, ResultCodeEnum.DATA_ERROR, "专辑不存在");
        ThrowUtil.throwIf(!userId.equals(albumInfo.getUserId()), ResultCodeEnum.PERMISSION, "无权限修改该专辑");
        albumInfoService.updateAlbumInfo(id, albumSaveOrUpdateDTO);
        return Result.ok();
    }

    @GetMapping("/albumInfo/getAlbumStatVo/{albumId}")
    @Operation(tags = "获取专辑统计信息")
    public Result<AlbumStatVo> getAlbumStatVo(@PathVariable Long albumId) {
        AlbumStatVo albumStatVo = albumInfoService.getAlbumStatVo(albumId);
        return Result.ok(albumStatVo);
    }
}
